package com.oa.web.base.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.oa.resources.consts.AppConsts;
import com.oa.resources.util.LogUtil;
import com.oa.resources.util.enums.LogType;
import com.oa.service.base.entity.User;

/**
 *
 * 文件名： com.oa.web.base.interceptor.LoginInterceptor.java
 * 作者：   WenBin
 * 日期：   2017年4月29日
 * 功能说明：
 *
 * =========================================================
 * 修改记录：
 * 修改作者    日期      修改内容
 *
 *
 * =========================================================
 *  Copyright (c) 2010-2011 .All rights reserved.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	public LoginInterceptor(){}

	private static final String[] IGNORE_URL = { "/system/login", "/system/logout" ,"/static"};

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean flag = true;
		String url = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		String actionUrl = url.substring(url.indexOf(contextPath) + contextPath.length());
		String requestType = request.getHeader("X-Requested-With");
		LogUtil.LOG(LogType.INFO, "请求类型：{}  访问路径：{}", requestType, actionUrl);
		for (String s : IGNORE_URL) {
			if (actionUrl.contains(s) || actionUrl.startsWith(s)) {
				LogUtil.LOG(LogType.INFO, "该路径是无需验证的路径:{}", actionUrl);
				flag = false;
				break;
			}
		}
		if (flag) {
			request.getSession().setAttribute(AppConsts.LAST_PAGE, actionUrl);
			User user = (User) request.getSession().getAttribute(AppConsts.USER_INFO);
			if (user == null) {
				response.sendRedirect(request.getContextPath() + "/system/login");
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		super.postHandle(request, response, handler, modelAndView);
	}
}
